import { MciSvgIcon } from '@/components/base';
import { useNodeResults } from '@/store/node-results';
import { ElTooltip, ElTree } from 'element-plus';
import { onBeforeRouteLeave } from 'vue-router';
import { Tree, TreeLabel } from './types';
import { ADMIN_ROLECODE } from '@/constants/config';
import { useAppStore } from '@/store/app';
import { useRole } from '@/hooks/useRole';
import './index.scss';
import { postDecisionListWithCategory, postDecisionFlowListByVersion } from '@/api';
import { AddMenuDecision } from '../AddMenuDecision';
import { AddDecision } from '../AddDecision';
import { DecisionLeafMore } from '../DecisionLeafMore';

export const DecisionList = defineComponent({
  setup(props, { expose }) {
    const listVisible = ref(false);
    const openMenu = ref(false);
    const route = useRoute();
    const router = useRouter();
    const loading = ref(false);
    const categoryList = ref<Array>([]);
    const execResultsStore = useNodeResults();
    const adminBtn = ref(false);
    const flowVersionList = ref<Array>([]);

    const appStore = useAppStore();

    onBeforeRouteLeave(() => {
      execResultsStore.clearResults();
    });

    const defaultExpanded = computed(() => {
      return route.query.decisionId as string;
    });

    const flowId = computed(() => {
      return route.query.flowId as string;
    });

    const treeRef = ref<InstanceType<typeof ElTree>>();

    const getList = async (pageNo = 1) => {
      try {
        loading.value = true;
        const categoryRes = await postDecisionListWithCategory();
        if (categoryRes && categoryRes.length !== 0) {
          const parentNodes: Tree[] = categoryRes.map((item) => ({
            id: item.id,
            name: item.categoryName,
            children: item.flows.map((flow) => ({
              parentId: item.id,
              parentName: item.categoryName,
              flowId: flow.id,
              flowName: flow.flowName,
              flowDesc: flow.flowDesc ? flow.flowDesc : '',
              versionFlow: flow.decisionFlow,
              flow,
              id: flow.decisionFlow?.id,
              decisionId: flow.decisionFlow?.decisionId,
              categoryId: flow.decisionFlow?.categoryId
            })),
            leaf: true
          }));
          // 遍历所有节点异步获取权限
          const promises = parentNodes.flatMap((parentNode) => useRole(null, parentNode?.id as string).initFlowDisabled());
          const allPermissionRoles = await Promise.all(promises);
          // 将获取到的权限信息分配给相应的节点
          parentNodes.forEach((parentNode, index) => {
            parentNode.permissionRoles = allPermissionRoles[index];
            if (parentNode.children) {
              parentNode.children.forEach((childNode) => {
                childNode.permissionRoles = parentNode.permissionRoles;
              });
            }
          });
          setTimeout(() => {
            treeRef.value?.setCurrentKey(defaultExpanded.value);
          }, 1);
          categoryList.value = parentNodes;
        } else {
          categoryList.value = [];
        }
      } catch (error) {
      } finally {
        loading.value = false;
      }
    };

    const getListByVersion = async (decisionId: string) => {
      if (!decisionId) return;
      const data = await postDecisionFlowListByVersion({ decisionId });
      flowVersionList.value = data;
      if (data.length === 0) return;
      const detailList = data.filter(item => item.status === 0 || item.status === 1);
      const newList = detailList.length > 0 ? detailList : data;
      const detailObj = newList[0];
      const detail = {
        flowId: detailObj.id,
        decisionId: detailObj.decisionId,
        categoryId: detailObj.categoryId,
      };
      router.push({
        name: 'DecisionFlow',
        query: detail
      });
    };

    const getListByVersionList = () => {
      return flowVersionList.value;
    };

    const redirectDetail = (data: any) => {
      if (data.decisionId) {
        getListByVersion(data.decisionId);
      }
    };

    onMounted(() => {
      getList();
      adminBtn.value = appStore?.mcisaas?.roles?.some((item) => Number(item.roleCode) === ADMIN_ROLECODE);
    });

    expose({ refreshDecisionList: getList, getListByVersionList });

    return () => {
      return (
        <div class="h-full w-full z-10 bg-white flex flex-col bd-r">
          <div class="h-50px flex items-center justify-between px-12">
            <div class="text-value-14">决策列表</div>
            {adminBtn.value && (
              <div class="flex gap-12">
                <ElTooltip placement="top" content="新增目录">
                  <MciSvgIcon name="plus" onClick={() => (openMenu.value = true)} class="cursor-pointer" />
                </ElTooltip>
                <AddMenuDecision
                  v-model={openMenu.value}
                  title="新增目录"
                  onRefreshList={() => {
                    getList();
                  }}
                />
              </div>
            )}
          </div>
          <div class="decision-flow-list flex w-full flex-col overflow-y-auto" v-loading={loading.value}>
            <ElTree
              ref={treeRef}
              props={TreeLabel}
              data={categoryList}
              node-key="decisionId"
              // expand-on-click-node={false}
              highlight-current={true}
              // default-expanded-keys={[defaultExpanded.value]}
              current-node-key={defaultExpanded.value}>
              {(node) => {
                return (
                  <>
                    {node?.node.level === 1 ? (
                      <div
                        key={node?.data?.id}
                        onClick={() => (listVisible.value = false)}
                        class={['px-16 py-12 cursor-pointer decision-flow-item flex w-full justify-between']}>
                        <div class="max-w-[77%] truncate text-value-14">{node?.data?.name}</div>
                        <AddDecision
                          adminBtn={adminBtn.value}
                          categoryId={node?.data?.id}
                          permissionRoles={node?.data?.permissionRoles}
                          categoryName={node?.data?.name}
                          onRefreshList={() => {
                            getList();
                            listVisible.value = false;
                          }}
                        />
                      </div>
                    ) : (
                      <div
                        class="leaf-node"
                        key={node?.data?.id}
                        onClick={() => redirectDetail(node?.data)}
                        class={['px-16 py-12 cursor-pointer decision-flow-item flex w-full justify-between']}>
                        <div class="max-w-[77%] truncate text-value-14">{node?.data?.flowName}</div>
                        {/* {adminBtn.value && (
                          <div
                          class="action-list flex items-center gap-12"
                          onClick={(e) => {
                            e.stopPropagation();
                            visible.value = true;
                            flowLeaf.categoryId = node?.data?.flowId;
                            flowLeaf.categoryName = node?.data?.name;
                            flowLeaf.categoryDesc = node?.data?.desc;
                          }}> */}
                        {/* <ElTooltip placement="top" content="重命名"> */}
                        {/* <MciSvgIcon class="cursor-pointer outline-none leaf-more" name="more" /> */}
                        {/* </ElTooltip> */}
                        {/* </div> */}
                        {/* )} */}
                        <DecisionLeafMore
                          permissionRoles={node?.data?.permissionRoles}
                          parentId={node?.data?.parentId}
                          parentName={node?.data?.parentName}
                          flowId={node?.data?.flowId}
                          flowName={node?.data?.flowName}
                          flowDesc={node?.data?.flowDesc}
                          versionFlow={node?.data?.versionFlow}
                          onRefreshList={(refreshDetail: boolean) => {
                            getList();
                            if (refreshDetail) {
                              // flowContentRef.value?.refresh();
                            }
                          }}
                        />
                      </div>
                    )}
                  </>
                );
              }}
            </ElTree>
          </div>
        </div>
      );
    };
  }
});
